package com.otaliastudios.cameraview


import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.PorterDuff
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.otaliastudios.cameraview.livedata.MarkMapLiveData
import com.otaliastudios.cameraview.size.Size
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class MarkView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr),
    LifecycleObserver {
    val warterMap = MarkMapLiveData.get().value
    var launch: Job? = null
    var mLifecycle: Lifecycle? = null
    var rate = 500L
    var onSizeChangedCallback: ((size: Size) -> Unit)? = null
    private val bitmapArr = arrayOfNulls<BitmapData>(2)

    init {
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MarkView)
            rate = typedArray.getInt(R.styleable.MarkView_refresh_rate, 500).toLong()
            val scale = typedArray.getFloat(R.styleable.MarkView_refresh_scale, 1.0F)
            post {
                viewTreeObserver.addOnGlobalLayoutListener {
                    val size =
                        Size((measuredWidth * scale).toInt(), (measuredHeight * scale).toInt())
                    onSizeChangedCallback?.invoke(size)
                    if (bitmapArr[0]?.bitmap?.width != size.width || bitmapArr[0]?.bitmap?.height != size.height) {
                        LogPlus.w("一直变吗?==>${size}")
                        bitmapArr[0] = BitmapData(size)
                        bitmapArr[1] = BitmapData(size)
                    }
                }
            }

            typedArray.recycle()
        }
    }

    private fun updateMark(index: Int): Bitmap? {
        val bitmapData = bitmapArr[index]
        bitmapData?.canvas?.let { canvas ->
            canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR) // 清空画布
            warterMap.forEach {
                if (it.value.bitmap != null) {
                    canvas.drawBitmap(
                        it.value.bitmap!!, it.value.point.x.toFloat(),
                        it.value.point.y.toFloat(), it.value.paint
                    )
                } else {
                    val split = it.value.text.split("\\r?\\n".toRegex())
                    for ((i, str) in split.withIndex()) {
                        canvas.drawText(
                            str, it.value.point.x.toFloat(),
                            it.value.point.y.toFloat() + (i * it.value.textsize),
                            it.value.paint
                        )
                    }
                }
            }
        }
        return bitmapData?.bitmap

    }

    override fun onDetachedFromWindow() {
        launch?.cancel()
        super.onDetachedFromWindow()
    }

    fun setLifecycleOwner(owner: LifecycleOwner?) {
        if (owner == null) {
            clearLifecycleObserver()
        } else {
            clearLifecycleObserver()
            mLifecycle = owner.lifecycle
            mLifecycle?.addObserver(this)
        }
    }

    private fun clearLifecycleObserver() {
        mLifecycle?.removeObserver(this)
        mLifecycle = null

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        LogPlus.w("我来了==>开启")
        post {
            if (launch?.isActive == true) return@post
            launch = flow {
                repeat(Int.MAX_VALUE) {
                    delay(rate)
                    emit(it)

                }
            }.onEach {
                val bitmap = updateMark(it % 2)
                post { setImageBitmap(bitmap) }
            }.launchIn(GlobalScope)


        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        LogPlus.w("我来了==>关闭")
        launch?.cancel()
    }

    class BitmapData(size: Size) {
        val bitmap: Bitmap = Bitmap.createBitmap(size.width, size.height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)
    }

}